//从前序与中序遍历序列构造二叉树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    unordered_map<int, int> index;

public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for (int i = 0; i < preorder.size(); i++) {
            index[inorder[i]] = i;
        }
        return dfs(preorder, 0, n - 1, inorder, 0, n - 1);
    }
    TreeNode* dfs(vector<int>& preorder, int l1, int r1, vector<int>& inorder,
                  int l2, int r2) {
        if (l1 > r1 || l2 > r2)
            return nullptr;

        int t = preorder[l1];
        int t_index = index[t];
        int left_size = t_index - l2;
        TreeNode* root = new TreeNode(t);

        root->left =
            dfs(preorder, l1 + 1, l1 + left_size, inorder, l2, t_index - 1);
        root->right =
            dfs(preorder, l1 + 1 + left_size, r1, inorder, t_index + 1, r2);

        return root;
    }
};

//437. 路径总和 III
class Solution {
public:
    int rootSum(TreeNode* root, long long targetSum) {
        if (!root) {
            return 0;
        }

        int ret = 0;
        if (root->val == targetSum) {
            ret++;
        } 

        ret += rootSum(root->left, targetSum - root->val);
        ret += rootSum(root->right, targetSum - root->val);
        return ret;
    }

    int pathSum(TreeNode* root, int targetSum) {
        if (!root) {
            return 0;
        }
        
        int ret = rootSum(root, targetSum);
        ret += pathSum(root->left, targetSum);
        ret += pathSum(root->right, targetSum);
        return ret;
    }
};